<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Zongheng
 *
 * @author Implement <hdjahs@qq.com>
 */

header("Content-type: text/html; charset=utf-8");
include_once  BASE_PATH . '/Tool/Tool.php';
include_once  BASE_PATH . '/Tool/lib/LIB_http.php';
include_once  BASE_PATH . '/Tool/lib/LIB_parse.php';
include_once  BASE_PATH . '/Tool/lib/LIB_resolve_addresses.php';
include_once  BASE_PATH . '/Tool/lib/LIB_http_codes.php';

class Zongheng {

    private $url = "";
    public $result = '';
    public $str = '';
    public $key = '';
    public $baseKey = '';

    public function init($keys) {
        $url = "http://search.zongheng.com/search/all/%s/1.html";
        $this->createPath();
        foreach ($keys as $key) {
            $this->str = '';
            $this->result = '';
            $this->baseKey = $key;
            $this->key = iconv('utf-8', 'gbk', $key);                
            $this->url = sprintf($url, urlencode($key));
            if (!$this->isDown()) {
                $this->run();
            }
        }
    }

    public function createPath() {
        $txtPath = BASE_PATH . '/Log/txt/';
        $tmpPath = BASE_PATH . '/Log/tmp/';
        $imgPath = BASE_PATH . '/Log/img/';
        $tool = Tool::getIns();
        $tool->createPath($txtPath);
        $tool->createPath($tmpPath);
        $tool->createPath($imgPath);
    }

    public function isDown() {
        return false;
        $imgPath = BASE_PATH . '/Log/tmp/' . md5($this->key) . '.txt';
        if (file_exists($imgPath)) {
            return true;
        }
        return false;
    }

    public function run() {
        $this->getResult();
        $this->getSaveData();
        $obj = new SaveToFile($this);
        $obj->save();                                                               
        $this->saveFinish();
    }

    public function saveFinish() {
        $filePath = BASE_PATH . '/Log/tmp/' . md5($this->key) . '.txt';
        file_put_contents($filePath, 1);
    }

    public function getSaveData() {   
        if (!empty($this->result)) {
            new ZonghengDecoratorTitle($this);
            new ZonghengDecoratorDesc($this);
        }
    }

    public function getResult() {
        $download_page = http_get($this->url, $ref = "");
        $this->result = isset($download_page['FILE']) ? $download_page['FILE'] : '';
    }

}
